﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.SharePoint;
using Sapphire.Linq.Framework;

namespace Sapphire.Linq.FieldMaps
{
    public class MapsContext : IPropertyMapsContext
    {
        private readonly List<PropertyMap> _maps = new List<PropertyMap>();

        public PropertyMap<T> Register<T>(ListQuery<T> listQuery)
        {
            var propertyMap = new PropertyMap<T>(listQuery);
            _maps.Add(propertyMap);
            return propertyMap;
        }

        public SPField GetField<T>(SPList list, string propertyName)
        {
            var registeredMap = _maps.OfType<PropertyMap<T>>()
                .Where(m => m.List == list)
                .FirstOrDefault();

            if (registeredMap == null)
                return list.Fields.GetFieldByInternalName(propertyName);

            return registeredMap.FindField(list, propertyName);
        }

        public XElement GetFieldRef(Type objectType, string propertyName)
        {
            var registeredMap = _maps.Where(m => m.GetType().GetGenericArguments()[0] == objectType).FirstOrDefault();

            if (registeredMap == null)
                return XElement.Parse(string.Format("<FieldRef Name=\"{0}\"/>", propertyName));

            return registeredMap.GetFieldRef(objectType, propertyName);
        }
    }

}